package com.ruoyi.common.utils.rabbitmq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author xudengyu
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "spring.rabbitmq.listener.simple.retry",name = "enabled",havingValue = "true")
public class RabbitMQErrorConfig {

    public static final String ERR_EXCHANGE="err.exchange";
    public static final String ERR_QUEUE="err.queue";
    public static final String ERR_ROUTING_KEY="err.key";

    @Bean("errExchange")
    public Exchange errExchange(){
        return ExchangeBuilder.directExchange(ERR_EXCHANGE).build();
    }

    @Bean("errQueue")
    public Queue errQueue(){
        return QueueBuilder.durable(ERR_QUEUE).build();
    }

    @Bean("errBinding")
    public Binding errBinding(@Qualifier("errQueue") Queue queue, @Qualifier("errExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(ERR_ROUTING_KEY).noargs();
    }

    @Bean("messageRecoverer")
    public MessageRecoverer messageRecoverer(RabbitTemplate rabbitTemplate){
        log.error("ready to errqueue");
        return new RepublishMessageRecoverer(rabbitTemplate,ERR_EXCHANGE,ERR_ROUTING_KEY);
    }

}